import { useCallback } from 'react';
import { useSnackbar } from 'notistack';

interface FileImportOptions<T> {
  accept?: string;
  maxSize?: number; // 字节
  validator?: (data: unknown) => data is T;
  onSuccess: (data: T) => void;
  onError?: (error: Error) => void;
}

/**
 * 通用文件导入 Hook
 * 提供文件导入功能，支持文件验证、大小限制和错误处理
 */
export function useFileImport<T = unknown>() {
  const { enqueueSnackbar } = useSnackbar();

  const importFile = useCallback(
    (options: FileImportOptions<T>) => {
      const {
        accept = '.json',
        maxSize = 10 * 1024 * 1024, // 默认 10MB
        validator,
        onSuccess,
        onError,
      } = options;

      const input = document.createElement('input');
      input.type = 'file';
      input.accept = accept;

      input.onchange = async (event) => {
        const file = (event.target as HTMLInputElement).files?.[0];
        if (!file) {
          enqueueSnackbar('未选择文件。', { variant: 'info' });
          return;
        }

        // 文件大小检查
        if (file.size > maxSize) {
          const maxSizeMB = (maxSize / 1024 / 1024).toFixed(0);
          enqueueSnackbar(`文件过大，请选择小于 ${maxSizeMB}MB 的文件。`, {
            variant: 'error',
          });
          return;
        }

        const reader = new FileReader();
        reader.onerror = () => {
          const error = new Error('文件读取失败，请重试。');
          enqueueSnackbar(error.message, { variant: 'error' });
          onError?.(error);
        };

        reader.onload = async (e) => {
          try {
            const content = e.target?.result as string;
            if (!content) {
              throw new Error('文件内容为空');
            }

            // 解析 JSON
            let parsedJson: unknown;
            try {
              parsedJson = JSON.parse(content);
            } catch {
              throw new Error('JSON 文件格式不正确。请检查文件内容。');
            }

            // 验证数据
            if (validator && !validator(parsedJson)) {
              throw new Error('文件格式验证失败');
            }

            // 调用成功回调
            onSuccess(parsedJson as T);
            enqueueSnackbar('导入成功！', { variant: 'success' });
          } catch (error) {
            const errorMessage =
              error instanceof Error ? error.message : '导入失败：未知错误';
            enqueueSnackbar(errorMessage, { variant: 'error' });
            if (error instanceof Error) {
              onError?.(error);
            }
          }
        };

        reader.readAsText(file);
      };

      input.click();
    },
    [enqueueSnackbar]
  );

  return { importFile };
}

